const {Email, Head} = require('../untils/config')
const UserModel = require('../models/User')
const fs = require('fs')
const url = require('url')
const {setCrypto, createVerifyImg} = require('../untils/base')

const login = async (req,res) => {
  let {username, password, verifyImg} = req.body
  if(verifyImg !== req.session.verifyImg) {
    res.send({
      msg:'验证码输入不正确',
      status: -3
    })
    return 
  }
  const result = await UserModel.login({username, password: setCrypto(password)})
  if(result) {
    req.session.username = username
    req.session.isAdmin = result.isAdmin
    req.session.avatar = result.avatar
    if(result.isFreeze) {
      res.send({
        msg:'账户已冻结',
        status: -2
      })
    }else{
      res.send({
        msg:'登录成功',
        status: 0
      })
    }  
  }else {
    res.send({
      msg:'登录失败',
      status: -1
    })
  }
}
const register = async (req,res) => {
  let {username, password, verify, email, isAdmin} = req.body;
  if(verify !== req.session.verify || email !== req.session.email) {
    res.send({
       msg: '验证码错误',
      status: -1
    })
    return 
  }

  if(Email.time - req.session.time > 1*60*1000) {
    res.send({
      msg: '验证码已失效',
      status: -3
    })
    return
  }

  if(isAdmin === 0) {
    isAdmin: false
  }else if (isAdmin === 1) {
    isAdmin: true
  }

  let result = await UserModel.save({
    username,
    password: setCrypto(password),
    email,
    isAdmin
  })
  if(result) {
    res.send({
      msg: '注册成功',
      status: 0
    })
  }else{
    res.send({
      msg: '注册失败',
      status: -2
    })
  }
}
const verify = async (req,res) => {
  const email = req.query.email
  const verify = Email.verify

  req.session.verify = verify
  req.session.email = email
  req.session.time = Email.time

  const mailOptions = {
    from: '"喵喵网" 935840006@qq.com', // sender address
    to: email, // list of receivers
    subject: "喵喵网邮箱验证码", // Subject line
    text: "验证码：" + verify, // plain text body
  }
  
  Email.transporter.sendMail(mailOptions, (err, info) => {
    if(err) {
      res.send({
        msg: '验证码发送失败',
        status: -1
      })
    }else {
      res.send({
        msg: '验证码发送成功',
        status: 0
      })
    }
  })
}
const logout = async (req,res) => {
  req.session.username = ''
  res.send({
    msg: '退出成功',
    status: 0
  })
}
const getUser = async (req,res) => {
  if(req.session.username) {
    res.send({
      msg: '获取用户信息成功',
      status: 0,
      data: {
        username: req.session.username,
        isAdmin: req.session.isAdmin,
        isFreeze: req.session.isFreeze,
        avatar: req.session.avatar,
      }
    })
  }else {
    res.send({
      msg: '获取用户信息失败',
      status: -1,
    })
  }
}
const updatePassword = async (req,res) => {
  let {email,password, verify } = req.body

  if(email === req.session.email && verify === req.session.verify) {
    let result = await UserModel.updatePassword(email, setCrypto(password))
    if(result) {
      res.send({
        msg: '修改密码成功',
        status: 0
      })
    }else {
      res.send({
        msg: '修改密码失败',
        status: -1
      })
    }
  }else {
    res.send({
      msg: '验证码错误',
      status: -1
    })
  }
}

const createVerify = async (req,res) => {
  let result = await createVerifyImg()
  if(res) {
    req.session.verifyImg = result.token
    res.send(result.buffer)
  }
}

const uploadAvatar = async(req, res) => {
  await fs.rename('public/uploads/'+req.file.filename,'public/uploads/'+req.session.username+'.jpg', err => console.log(err))

  let result = await UserModel.uploadAvatar(req.session.username, url.resolve(Head.baseUrl, req.session.username + '.jpg'))
  if(result) {
    res.send({
      msg: '头像上传成功',
      status: 0,
      data:{
        avatar: url.resolve(Head.baseUrl, req.session.username + '.jpg')
      }
    })
  }else {
    res.send({
      msg: '头像上传失败',
      status: -1
    })
  }
}

module.exports = {
  login,register,verify,logout,getUser,updatePassword,createVerify,uploadAvatar,
}